package com.hanxiaozhang.base.service.impl;


import com.hanxiaozhang.base.dao.GeneratorDao;
import com.hanxiaozhang.base.entity.ColumnEntity;
import com.hanxiaozhang.base.entity.TableEntity;
import com.hanxiaozhang.base.service.GeneratorService;
import com.hanxiaozhang.base.util.GeneratorUtil;
import com.hanxiaozhang.config.GeneratorProperties;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 生成代码
 *
 * @author hanxiaozhang
 * @email hanxiaozhang2018@sina.com
 * @date 2021-04-23
 */
@Service
public class GeneratorServiceImpl implements GeneratorService {

    @Resource
    private GeneratorDao generatorDao;
    @Autowired
    private GeneratorProperties generatorProperties;


    @Override
    public List<TableEntity> listTable() {

        List<TableEntity> list = generatorDao.listTable();
        return list;
    }

    @Override
    public GeneratorProperties getConfig() {
        return generatorProperties;
    }


    @Override
    public void updateConfig(Map<String, Object> params) {

        generatorProperties.setAuthor(params.get("author").toString())
                .setEmail(params.get("email").toString())
                .setSince(params.get("since").toString())
                .setPackagePath(params.get("packagePath").toString())
                .setTablePrefix(params.get("tablePrefix").toString())
                .setRemoveTablePrefix((boolean) params.get("removeTablePrefix"));
    }


    @Override
    public byte[] generatorCode(List<String> tableNames) {

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            //查询表信息
            TableEntity table = generatorDao.getTableByTableName(tableName);
            //查询列信息
            List<ColumnEntity> columns = generatorDao.listColumnByTableName(tableName);
            //生成代码
            GeneratorUtil.generatorCode(table, columns, generatorProperties, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }


}
